package com.example.device.polling

import android.app.TimePickerDialog
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.example.common.view.view.BaseMvvmActivity
import com.example.device.R
import com.example.device.databinding.ActivityPollingEditBinding
import com.example.device.entity.Device
import com.example.device.entity.PollingEntity
import com.example.device.vm.PollingEditViewModel
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
@Route(path = "/device/PollingEditActivity")
class PollingEditActivity : BaseMvvmActivity<ActivityPollingEditBinding>() {
    override fun getLayoutId(): Int = R.layout.activity_polling_edit
    // 巡逻频次按钮状态
    private var frequencySelected = 0 // 0: 每天, 1: 工作日, 2: 周末

    // 巡逻状态按钮状态
    private var statusSelected = 0 // 0: 启用, 1: 停用

    // 巡逻时间
    private var startTime = "09:00"
    private var endTime = "17:00"

    private val pollingEditViewModel : PollingEditViewModel by viewModels()

    private var nfc = 0
    override fun initView() {
        super.initView()

        // 初始化巡逻频次按钮样式
        updateFrequencyButtonStyle()

        // 初始化巡逻状态按钮样式
        updateStatusButtonStyle()

        // 初始化时间显示
        mDataBinding.startTimeText.text = startTime
        mDataBinding.endTimeText.text = endTime


        // 时间选择器点击事件
        mDataBinding.startTimeText.setOnClickListener {
            showTimePicker(true)
        }

        mDataBinding.endTimeText.setOnClickListener {
            showTimePicker(false)
        }

        mDataBinding.addCheckPointBtn.setOnClickListener {
            ARouter.getInstance().build("/device/PollingNFCAddActivity").navigation()
        }
        mDataBinding.nfc1.setOnClickListener {
            nfc = 1
            ARouter.getInstance().build("/device/PollingNFCActivity").navigation()
        }
        mDataBinding.nfc2.setOnClickListener {
            nfc = 0
            ARouter.getInstance().build("/device/PollingNFCActivity").navigation()
        }
        // 巡逻频次按钮点击事件
        mDataBinding.dailyBtn.setOnClickListener {
            frequencySelected = 0
            updateFrequencyButtonStyle()
        }
        mDataBinding.workdayBtn.setOnClickListener {
            frequencySelected = 1
            updateFrequencyButtonStyle()
        }
        mDataBinding.weekendBtn.setOnClickListener {
            frequencySelected = 2
            updateFrequencyButtonStyle()
        }
        // 巡逻状态按钮点击事件
        mDataBinding.enableBtn.setOnClickListener {
            statusSelected = 0
            updateStatusButtonStyle()
        }
        mDataBinding.disableBtn.setOnClickListener {
            statusSelected = 1
            updateStatusButtonStyle()
        }
        mDataBinding.saveBtn.setOnClickListener {
            val pollingEntity = PollingEntity(
             address= if (nfc ==1) "" else  "",//address 工单地址
             appointmentTime="${mDataBinding.startTimeText.text}T${mDataBinding.endTimeText.text}",//appointmentTime 预约时间
             content=mDataBinding.content.text.toString(),//content 工单内容描述
             deviceInspections= listOf(Device(id = 1, device = "设备A", inspected = false)),//deviceInspections 设备检查项列表
             id=0,//id 工单唯一标识符
             inspector= mDataBinding.patrolPersonSpinner.text.toString(),//inspector 检查员姓名
             orderType= "设备巡检",//orderType 工单类型
             photos= listOf(""),//photos 现场照片URL列表
             status= "新建" // status 工单状态
            )
            pollingEditViewModel.postPolling(pollingEntity)
        }
        pollingEditViewModel.mSuccessLiveData.observe(this){
            ToastUtils.showLong("提交成功")
            finish()
        }
        pollingEditViewModel.mErrorLiveData.observe(this){
            ToastUtils.showLong(it)
        }
    }
    /**
     * 显示时间选择器
     * @param isStartTime Boolean 是否是开始时间
     */
    private fun showTimePicker(isStartTime: Boolean) {
        // 解析当前时间
        val timeParts = if (isStartTime) {
            startTime.split(":")
        } else {
            endTime.split(":")
        }
        val hour = timeParts[0].toInt()
        val minute = timeParts[1].toInt()

        // 创建时间选择器
        val timePickerDialog = TimePickerDialog(
            this,
            { _, selectedHour, selectedMinute ->
                val timeString = String.format("%02d:%02d", selectedHour, selectedMinute)
                if (isStartTime) {
                    startTime = timeString
                    mDataBinding.startTimeText.text = startTime
                } else {
                    endTime = timeString
                    mDataBinding.endTimeText.text = endTime
                }
            },
            hour,
            minute,
            true // 24小时制
        )

        timePickerDialog.show()
    }
    /**
     * 创建带边框的背景
     */
    private fun createBorderDrawable(): GradientDrawable {
        val drawable = GradientDrawable()
        drawable.shape = GradientDrawable.RECTANGLE
        drawable.setStroke(2, ContextCompat.getColor(this, com.example.resource.R.color.blue)) // 2px蓝色边框
        drawable.cornerRadius = 8f // 设置圆角
        return drawable
    }

    /**
     * 更新巡逻频次按钮样式
     */
    private fun updateFrequencyButtonStyle() {
        val selectedColor = ContextCompat.getColor(this, com.example.resource.R.color.blue)
        val selectedTextColor = Color.WHITE
        val defaultTextColor = ContextCompat.getColor(this, R.color.black)
        val borderDrawable = createBorderDrawable()

        // 重置所有按钮样式
        mDataBinding.dailyBtn.background = borderDrawable
        mDataBinding.dailyBtn.setTextColor(defaultTextColor)
        mDataBinding.workdayBtn.background = borderDrawable
        mDataBinding.workdayBtn.setTextColor(defaultTextColor)
        mDataBinding.weekendBtn.background = borderDrawable
        mDataBinding.weekendBtn.setTextColor(defaultTextColor)

        // 设置选中按钮样式
        when (frequencySelected) {
            0 -> {
                mDataBinding.dailyBtn.setBackgroundColor(selectedColor)
                mDataBinding.dailyBtn.setTextColor(selectedTextColor)
            }
            1 -> {
                mDataBinding.workdayBtn.setBackgroundColor(selectedColor)
                mDataBinding.workdayBtn.setTextColor(selectedTextColor)
            }
            2 -> {
                mDataBinding.weekendBtn.setBackgroundColor(selectedColor)
                mDataBinding.weekendBtn.setTextColor(selectedTextColor)
            }
        }
    }

    /**
     * 更新巡逻状态按钮样式
     */
    private fun updateStatusButtonStyle() {
        val selectedColor = ContextCompat.getColor(this, com.example.resource.R.color.blue)
        val selectedTextColor = Color.WHITE
        val defaultTextColor = ContextCompat.getColor(this, R.color.black)
        val borderDrawable = createBorderDrawable()

        // 重置所有按钮样式
        mDataBinding.enableBtn.background = borderDrawable
        mDataBinding.enableBtn.setTextColor(defaultTextColor)
        mDataBinding.disableBtn.background = borderDrawable
        mDataBinding.disableBtn.setTextColor(defaultTextColor)

        // 设置选中按钮样式
        when (statusSelected) {
            0 -> {
                mDataBinding.enableBtn.setBackgroundColor(selectedColor)
                mDataBinding.enableBtn.setTextColor(selectedTextColor)
            }
            1 -> {
                mDataBinding.disableBtn.setBackgroundColor(selectedColor)
                mDataBinding.disableBtn.setTextColor(selectedTextColor)
            }
        }
    }
}
